/**
 * 
 */
package com.ginger.rabbitmq.exchange.api.returnlistener;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ginger.properties.RabbitMQProperties;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ReturnListener;

/**
 * @Description: 生产者
 * @author 姜锋
 * @date 2019年3月29日 上午9:40:05
 * @version V1.0
 */
public class Producer {
	/** 日志对象 **/
	private final static Logger logger = LoggerFactory.getLogger(Producer.class);
	public static void main(String[] args) throws Exception {
		// 1.创建连接工厂
		ConnectionFactory connectionFactory = new ConnectionFactory();
		// 1.1设置连接信息
		connectionFactory.setHost(RabbitMQProperties.RABBITMQ_HOST);
		connectionFactory.setPort(RabbitMQProperties.RABBITMQ_PORT);
		connectionFactory.setVirtualHost(RabbitMQProperties.RABBITMQ_VIRTUAL_HOST);
		connectionFactory.setUsername(RabbitMQProperties.USER_NAME);
		connectionFactory.setPassword(RabbitMQProperties.PASSWORD);
		// 2.通过连接工厂创建连接
		Connection connection = connectionFactory.newConnection();
		// 3.通过connection创建
		Channel channel = connection.createChannel();
		// 4.声明
		String exchangeName = "test_return_exchange";
		String routingKey = "return.save";
		String routingKeyError = "abc.save";
		// 5. 添加Return监听
		channel.addReturnListener(new ReturnListener() {
			@Override
			public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
					AMQP.BasicProperties properties, byte[] body) throws IOException {
				
				logger.info("----- handle return -----");
				logger.info("replyCode:" + replyCode);
				logger.info("replyText:" + replyText);
				logger.info("exchange:" + exchange);
				logger.info("routingKey:" + routingKey);
				logger.info("properties:" + properties);
				logger.info("body:" + new String(body));
			}
			
		});
		// 6.通过channel发送数据
		// for (int i = 0; i < 5; i++) {
		String message = "这是 1条生产的数据:  Hello RabbitMQ Send Return message !";
		// channel.basicPublish(交换机名称, RouttingKey, properties, 内容);
		channel.basicPublish(exchangeName, routingKey, true, null, message.getBytes());
		channel.basicPublish(exchangeName, routingKeyError, true, null, message.getBytes());
		// }
	}
}
